<?php
namespace app\logic;

use app\models\Manager;
use app\models\Order;
use app\models\Shop;
use app\models\User;
use Yii;
use yii\db\Query;


class UserLogic
{
    public function createCancelNo(){
        return mt_rand(10000000,99999999);
        /*$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));*/
    }

    public function createOrderNo(){
        return date('Ymd').mt_rand(100000,999999);
        /*$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));*/
    }
    public function addCard($id,$params){

        $order_no = $this->createOrderNo();
        $order2 = Order::findOne(['order_no'=>$order_no]);
        while($order2){
            $order_no = $this->createOrderNo();
            $order2 = Order::findOne(['order_no'=>$order_no]);
        }
        $cancel_no = $this->createCancelNo();
        $order3 = Order::findOne(['cancel_no'=>$cancel_no]);
        while($order3){
            $cancel_no = $this->createCancelNo();
            $order3 = Order::findOne(['cancel_no'=>$cancel_no]);
        }

        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $order = new Order();
        $user = User::findOne($id);
        $playLogic = new PlayLogic();
        $play = $playLogic->getById($params['play_id']);

        $order->order_no = $order_no;
        $order->cancel_no = $cancel_no;
        $order->type = 0;
        $order->status = 1;
        $order->gp_id = $params['play_id'];
        $order->price = $play['price'];
        $order->current_num = $play['num'];
        $order->order_time = date('Y-m-d H:i:s');
        $expire_time = date('Y-m-d', strtotime("+".$play['expire_time']." day"));
        $order->expire_time = $expire_time;
        $order->user_id = $id;
        $order->shop_id = 0;
        $order->ext_price = $play['ext_price'];
        $order->remark = $params['remark'];
        $result1 = $order->save();
        $user->current_num += $play['num'];
        $result2 = $user->save();
        if($result1 && $result2){
            $transaction->commit();
            return true;
        }else{
            $transaction->rollBack();
            return false;
        }
    }
    public function getUser($query = [], $page = 1, $limit = 10)
    {
        $user = User::find()->filterWhere($query)->orderBy('user_id desc')
            ->offset(($page - 1) * $limit)->limit($limit);
        $lists = $user->asArray()->all();
        $return = [
            'lists' => $lists,
            'pager' => [
                'total' => $user->count(),
                'page' => $page,
                'limit' => $limit,
                'url' => 'user/index',
                'query' => $query
            ]
        ];
        return $return;
    }



    public function addUser($params){
        if(User::findOne(['phone'=>$params['phone']])){
            return false;
        }else{
            $user = new User();
            $user->phone = $params['phone'];
            $user->type = $params['type'];
            $user->create_time = date('Y-m-d H:i:s');
            $user->status = 0;
            return $user->save();
        }
    }

    public function editUserById($id, $params)
    {
        if(!$user = User::findOne($id))
            return false;
        $check = User::find()->where("user_id!=$id AND phone='".$params['phone']."'")->one();
        if($check)
            return ['result'=>false,'msg'=>'该手机号已存在'];
        $shop = Shop::findOne(['owner_user_id'=>$id]);
        if($shop && ($params['type']==0 || $params['type']==2))
            return ['result'=>false,'msg'=>'该用户已绑定为店主，请先解除店主合同'];
        $manager = Manager::findOne(['user_id'=>$id]);
        if($manager && ($params['type']==0 || $params['type']==1))
            return ['result'=>false,'msg'=>'该用户已绑定为店长，请先解除店长合同'];
        $user->phone = $params['phone'];
        $user->type = $params['type'];
        if($user->save()){
            return ['result'=>true];
        }
    }

    public function saveStatus($id)
    {
        $user = User::findOne($id);
        if($user->status)
            $user->status = 0;
        else
            $user->status = 1;
        return $user->save();
    }

    public function getManager($user_id){
        if($manager = Manager::findOne(['user_id'=>$user_id]))
            return $manager->toArray();
        else
            return false;
    }

    public function getById($user_id){
        return User::findOne($user_id)->toArray();
    }

    public function getAllNotOUser()
    {
        return User::find()->where(['status'=>1])->andWhere(['in','type',[1,2]])->asArray()->all();
    }

    public function getAllOwnerUser()
    {
        return User::find()->where(['status'=>1,'type'=>1])->asArray()->all();
    }

    public function addContract($params){
        $manager = new Manager();
        $manager->shop_id = $params['shop_id'];
        $manager->user_id = $params['user_id'];
        $manager->contract_start_time = $params['contract_start_time'] . " 00:00:00";
        $manager->contract_end_time = $params['contract_end_time'] . " 23:59:59";
        $manager->contract_create_time = date('Y-m-d H:i:s');
        $manager->manager_name = $params['name'];
        $manager_code = $this->createCancelNo();
        $manager3 = Manager::findOne(['manager_code'=>$manager_code]);
        while($manager3){
            $manager_code = $this->createCancelNo();
            $manager3 = Manager::findOne(['manager_code'=>$manager_code]);
        }

        $manager->manager_code = $manager_code;
        $manager->manager_code_pic = $this->scerweima($manager_code);

        return $manager->save();
    }

    public function scerweima($manager_code)
    {
        require_once(__DIR__ .'/../common/phpqrcode.php');

        $value = $manager_code;                    //二维码内容

        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 5;            //生成图片大小

        //生成二维码图片
        $filename = 'qrcode/' . $manager_code . '.png';
        \QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);

        $QR = $filename;                //已经生成的原始二维码图片文件
        return '/'.$filename;

        /*$QR = imagecreatefromstring(file_get_contents($QR));

        //输出图片
        imagepng($QR, 'qrcode.png');
        imagedestroy($QR);*/
    }


    public function editManager($id,$params){
        $manager = Manager::findOne($id);
        $manager->contract_start_time = $params['contract_start_time'] . " 00:00:00";
        $manager->contract_end_time = $params['contract_end_time'] . " 23:59:59";
        $manager->manager_name = $params['manager_name'];
        $manager->manager_code_pic = $this->scerweima($manager->manager_code);
        return $manager->save();
    }

    public function downloadCode($user_id){
        $manager = Manager::findOne(['user_id'=>$user_id]);
        require_once(__DIR__ .'/../common/phpqrcode.php');
        $value = $manager->manager_code;                    //二维码内容

        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 50;            //生成图片大小

        //生成二维码图片
        $filename = 'qrcode/' . $value . 'L.png';
        \QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
//echo(Yii::$app->params['domain']['back_all_domain'].'/'.$filename);exit;
        //获取要下载的文件名
        $filename = $value . 'L.png';
//设置头信息
        header('Content-Disposition:attachment;filename=' . basename($filename));
        //header('Content-Length:' . filesize($filename));
//读取文件并写入到输出缓冲
        readfile(__DIR__.'/../web/qrcode/'.$filename);

    }

    public function delManager($user_id){
        $manager = Manager::findOne(['user_id'=>$user_id]);
        return $manager->delete();
    }


}